<template>
	<view>
		<view class="auth">
			<view class="auth-title">输入短信验证码</view>
			<view class="auth-mobile">
				短信验证码至<text>{{mobile}}</text>
			</view>
			<view class="codes">
				<view v-for="item in config.count" :key="item.key">
					<view class="input" @tap="hanldeOpenKeyboard" :class="{ active: currentFocus == item.index }">
						<template v-if="code[item.index - 1] != undefined">
							{{ code[item.index - 1] }}
						</template>
						<template v-else>
							<view v-if="currentFocus == item.index" class="shining"></view>
						</template>
					</view>
				</view>
			</view>
			<view class="auth-again">
				<text v-if="countdown > 0" class="time">{{countdown}}秒后重新发送</text>
				<text v-if="countdown == 0" @tap="resend">重新发送</text>
				<text v-if="countdown < 50">没有收到验证码？</text>
				
			</view>
		</view>
		<view style="display: flex;width: 100%;position: fixed;z-index: 99;height: 100vh;top: 0;left: 0;background: #ccc;opacity: 0.6;" v-show="captchashow">
			
		</view>
		<view style="width: 100%;position: fixed;z-index: 100;;top: 260rpx;left: 0;background: white;padding: 10rpx 30rpx;" v-show="captchashow">		
			<view style="width: 100%;height: 120rpx;line-height: 120rpx;text-align: center;font-weight: 600;font-size: 36rpx;">
				<text>请输入图形验证码</text>
			</view>
			<view style="width: 100%;display: flex;justify-content: space-between; ">
				<view style="width: 63%;">
					<input type="text" style="width: 100%;border: 1px solid #ccc;height: 80rpx;line-height: 80rpx;padding: 0 10%;" placeholder="请输入右侧图形验证码" v-model="verCode">
				</view>
				<view style="width: 33%;">
					<view class="canvas-img-code" @click="refresh()">
						<canvas :style="{width:width+'px',height:height+'px'}" canvas-id="imgcanvas" @error="canvasIdErrorCallback"></canvas>
					</view>
					<text style="height: 80rpx;line-height: 80rpx;" @click="refresh()">
						看不清，换一张
					</text>
				</view>
			</view>
			<view style="width: 100%;margin-bottom: 30rpx;display: flex;">
				<button style="padding: 0rpx 80rpx;color: black;background: #ccc;font-size: 28rpx;" @click="quxiao">取消</button>
				<button style="padding: 0rpx 80rpx;color: white;background: red;;font-size: 28rpx;" @click="checkcaptcha">确认</button>
			</view>
		</view>
		<wanl-keyboard :open="keyboardVisible" @number="inputCode" @delete="deleteCode" @empty="emptyCode" @close="keyboardVisible = false" />
	</view>
</template>
<script>
	var _this;
export default {
	
	data() {
		return {
			config: {
				count: [
					{
						index: 1,
						key: 'valid-code-input-1'
					},
					{
						index: 2,
						key: 'valid-code-input-2'
					},
					{
						index: 3,
						key: 'valid-code-input-3'
					},
					{
						index: 4,
						key: 'valid-code-input-4'
					},
					{
						index: 5,
						key: 'valid-code-input-5'
					},
					{
						index: 6,
						key: 'valid-code-input-6'
					}
				]
			},
			keyboardVisible: true,
			currentFocus: 1,
			mobile: '',
			code: [],
			style: {
				inputWidth: '40upx',
				inputHeight: '100upx'
			},
			countdown: 60,
			cTimer: null,
			event: '',
			pageroute: '',
			captchashow:true,
			verCode: "", //验证码
			width: 120,
			height: 45
		};
	},
	onLoad(options) {
		this.mobile = options.mobile;
		this.event = options.event;
		this.pageroute = options.url;
		// this.getcaptcha();
		// this.sendMessage();
		// this.startTimer();
	},
	onShow() {
		_this = this;
		setTimeout(function() {
			_this.init();
		}, 100)
	},
	methods: {
		quxiao(){
			uni.navigateBack({
			    delta: 1 // 默认值是1，表示返回的页面层数
			});
		},
		init: function() {
			// console.log('start');
			var context = uni.createCanvasContext('imgcanvas', this),
				w = this.width,
				h = this.height;
			context.setFillStyle("white");
			context.setLineWidth(5);
			context.fillRect(0, 0, w, h);
			var pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",  "M", "N", "P", "Q", "R", "S",
					"T", "U", "V", "W", "S", "Y", "Z",  "2", "3", "4", "5", "6", "7", "8", "9"
				],
				str = '';
			for (var i = 0; i < 4; i++) {
				var c = pool[this.rn(0, pool.length - 1)];
				var deg = this.rn(-30, 30);
				context.setFontSize(20);
				context.setTextBaseline("top");
				context.setFillStyle(this.rc(80, 150));
				context.save();
				context.translate(30 * i + 15, parseInt(h / 1.5));
				context.rotate(deg * Math.PI / 180);
				context.fillText(c, -15 + 5, -15);
				context.restore();
				str += c;
			}
			uni.setStorage({
				key: 'imgcode',
				data: str,
			});
			for (var i = 0; i < 40; i++) {
				context.beginPath();
				context.arc(this.rn(0, w), this.rn(0, h), 1, 0, 2 * Math.PI);
				context.closePath();
				context.setFillStyle(this.rc(150, 200));
				context.fill();
			}
			context.draw();
			// console.log('end');
		},
		rc: function(min, max) {
			var r = this.rn(min, max);
			var g = this.rn(min, max);
			var b = this.rn(min, max);
			return "rgb(" + r + "," + g + "," + b + ")";
		},
		rn: function(max, min) {
			return parseInt(Math.random() * (max - min)) + min;
		},
		refresh: function() {
			this.init();
		},
		canvasIdErrorCallback: function(e) {
			console.error(e.detail.errMsg)
		},
		checkcaptcha(){
			if (this.verCode.toLowerCase() != uni.getStorageSync('imgcode').toLowerCase()) {
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '验证码不正确'
				});
			this.refresh()
			}else{
				this.captchashow=false
				this.sendMessage();
				this.startTimer();
			}
		},
		inputCode(e) {
			this.code[this.currentFocus - 1] = e;
			if (this.currentFocus == 6) {
				this.login();
			}
			if (this.currentFocus <= 6) {
				this.currentFocus++;
			}
		},
		login() {
			uni.showLoading();
			// 找回密码
			if (this.event == 'resetpwd') {
				this.$wanlshop.to(`resetpwd?mobile=${this.mobile}&captcha=${this.code.join("")}&url=${this.pageroute}`);
				uni.hideLoading();
			}
			// 绑定手机号
			if (this.event == 'changemobile') {
				this.$api.post({
				    url: '/wanlshop/user/changemobile', 
					data:{
						mobile: this.mobile,
						captcha: this.code.join(""),
						client_id: uni.getStorageSync("wanlshop:chat_client_id")?uni.getStorageSync("wanlshop:chat_client_id") : null
					},
				    success: res => {
						setTimeout(() => {
						this.$wanlshop.msg('绑定成功');
						},1000)
						// this.$store.dispatch('cart/login');s
						this.$store.dispatch('user/login', res);
						this.$store.dispatch('cart/login');
						 uni.reLaunch({url: decodeURIComponent('/pages/user')});
						// uni.switchTab({
						// 	url:'/pages/user'
						// })
				    }
				});
			}
			// 验证码登录
			if (this.event == 'mobilelogin') {
				this.$api.post({
				    url: '/wanlshop/user/mobilelogin', 
					data:{
						mobile: this.mobile,
						captcha: this.code.join(""),
						client_id: uni.getStorageSync("wanlshop:chat_client_id")?uni.getStorageSync("wanlshop:chat_client_id") : null
					},
				    success: res => {
						uni.hideLoading();
						// 中央控制总线
						this.$store.dispatch('user/login', res);
				        this.$store.dispatch('cart/login');
				        uni.reLaunch({url: decodeURIComponent(this.pageroute)});
				    }
				});
			}
			// 用户注册
			if (this.event == 'register') {
				this.$api.post({
				    url: '/wanlshop/user/register', 
					data:{
						mobile: this.mobile,
						captcha: this.code.join(""),
						client_id: uni.getStorageSync("wanlshop:chat_client_id")?uni.getStorageSync("wanlshop:chat_client_id") : null
					},
				    success: res => {
						uni.hideLoading();
						// 中央控制总线
						
						this.$store.dispatch('user/login', res);
						this.$store.dispatch('cart/login');
						this.$store.dispatch('chat/get');
				        uni.reLaunch({url: decodeURIComponent(this.pageroute)});
				    }
				});
			}
			this.currentFocus = 0;
			this.code = [];
		},
		deleteCode() {
			this.currentFocus--;
			this.code.splice(-1, 1);
		},
		emptyCode(){
			this.code = [];
			this.currentFocus = 0;
		},
		hanldeOpenKeyboard() {
			this.keyboardVisible = true;
		},
		sendMessage() {
			this.$api.get({
			    url: '/wanlshop/sms/send', 
				data:{
					event: this.event,  
					mobile: this.mobile
				},
				loadingTip: '验证码发送中...',
			    success: res => {
					this.$wanlshop.msg('验证码发送成功');
			    }
			});
		},
		startTimer() {
			if (this.cTimer == null) {
				this.cTimer = setInterval(() => {
					this.countdown--;
					if (this.countdown == 0) {
						this.clearTimer();
					}
				}, 1000)
			}
		},
		clearTimer() {
			clearInterval(this.cTimer);
			this.cTimer = null;
		},
		resend(){
			this.startTimer();
			this.code = [];
			this.currentFocus = 0;
			this.countdown = 60;
			this.sendMessage();
		}
	}
};
</script>

<style>
	@import url("auth.css");
</style>